我是Flutter的新手。我想在Flutter应用程序中加载txt文件,并将其每一行传递到列表索引。我编写了一个程序,该程序在ListView中显示列表的成员,但我希望列表从txt文件接收数据。
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
void main() => runApp(MyApp());
Future<String> loadAsset() async {
return await rootBundle.loadString('assets/data/table.txt');
}
class MyApp extends StatelessWidget {
final mylist = ['A', 'B', 'C'];
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(text: "فهرست"),
Tab(text: "علاقهمندیها"),
],
),
title: Text("my app"),
),
body: TabBarView(
children: [
ListView.builder(
itemBuilder: (context, position) {
return Card(
child: Text(mylist[position]),
);
},
itemCount: mylist.length,
),
ListView(
children: <Widget>[
Text('data'),
],
),
]
),
),
)
);
}
}
我将txt文件设置在项目目录中的文件夹(数据)中。这是我的“ pubspec.yaml”文件:
flutter:
assets:
- data/table.txt
这是我的txt文件(table.txt):
A
B
C