我在flutter的应用中实现了HTTP JSON请求和sqflite,但我不确定将数据从json同步到sqflite的最佳方法是什么。我的本能是将这些数据加载到main.dart中,但无法正常工作。我收到Future >>无法分配给List。如果将其加载到gridViewWidget中,是否为时已晚?我应该在GridViewWidget fetchFlashCardList方法中将json数据添加到数据库中吗?
main.dart:
void main() async {
var networkObj = new NetworkObject();
//Error Here
List<FlashCardList> flashCardList = networkObj.fetchFlashCardList();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
final Future<FlashCardList> flashCardList;
MyApp({Key key, this.flashCardList}): super (key:key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: new GridViewWidget(),
);
}
}
gridViewWidget.dart
class GridViewWidget extends StatefulWidget{
@override
createState() => new GridViewState();
}
class GridViewState extends State<GridViewWidget>{
List<FlashCardList> flashCardList;
Future<List<FlashCardList>> fetchFlashCardList() async{
final response = await http.get('https://babymozart.org/babymozartq92C9TLa9UMkulL2m81xHdn9u2R92e1e/flutter_test.json');
//debugPrint (response.body);
if (response.statusCode == 200) {
var data = json.decode(response.body);
var flashCardListData = data["FlashCardList"] as List;
flashCardList = flashCardListData.map<FlashCardList>((json) => FlashCardList.fromJson(json)).toList();
debugPrint("Did get data: ${flashCardList.first.name}");
} else {
throw Exception('Failed to load post');
}
//objects = [sound, flashCardList, flashCards].expand((x) => x).toList();
return flashCardList;
}
@override
void initState(){
debugPrint ('debug main.dart');
super.initState();
}
@override
Widget build(BuildContext context){
return new Scaffold(
appBar: new AppBar(
centerTitle: true,
title: new Text(Strings.pageTitle),
),
body: FutureBuilder<List<FlashCardList>>(
future: fetchFlashCardList(),
builder: (BuildContext context, AsyncSnapshot<List<Object>> snapshot) {
if (snapshot.hasError)
return new Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
if (snapshot.connectionState == ConnectionState.waiting){
new Center(child: new CircularProgressIndicator());
} else {
return new GridView.builder(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200.0,
childAspectRatio: MediaQuery.of(context).size.width/(MediaQuery.of(context).size.height)),
itemCount: flashCardList.length,
itemBuilder: (BuildContext context, int index) {
return _getGridItemUI(context, flashCardList[index]);
/*return GridTile(header: Text("FlashCards"),
child: Text(
flashCards[index].name, textAlign: TextAlign.center));*/
},
);
}
}
),
);
}
_getGridItemUI(BuildContext context, FlashCardList item){
return new InkWell(
onTap: () {
_showSnackBar(context, item);
},
child: new Card(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image(image: new CachedNetworkImageProvider("https://babymozart.org/babymozartq92C9TLa9UMkulL2m81xHdn9u2R92e1e/image/" + item.image)),
/*new Expanded(
child:new Center(
child: new Column(
children: <Widget>[
new SizedBox(height: 8.0),
new Expanded(
child: AutoSizeText(
item.name, maxLines: 1,
)
)
],
),
)
)*/
],
),
elevation: 2.0,
margin: EdgeInsets.all(5.0),
)
);
}
_showSnackBar(BuildContext context, FlashCardList item){
}
}