Flutter是一种跨平台的移动应用开发框架,可以帮助开发者快速构建高性能、美观的移动应用程序。在Flutter中,使用json和ListView导航到新屏幕可以通过以下步骤实现:
以下是一个示例代码:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:fluttertoast/fluttertoast.dart';
class ScreenPage extends StatefulWidget {
final String jsonData;
ScreenPage({Key key, @required this.jsonData}) : super(key: key);
@override
_ScreenPageState createState() => _ScreenPageState();
}
class _ScreenPageState extends State<ScreenPage> {
List<dynamic> data;
@override
void initState() {
super.initState();
data = jsonDecode(widget.jsonData);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('New Screen'),
),
body: ListView.builder(
itemCount: data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(data[index]['title']),
subtitle: Text(data[index]['subtitle']),
onTap: () {
Fluttertoast.showToast(
msg: 'You tapped on ${data[index]['title']}',
toastLength: Toast.LENGTH_SHORT,
);
},
);
},
),
);
}
}
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<List<dynamic>> fetchData() async {
final response = await http.get('https://api.example.com/data');
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('Failed to load data');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter JSON ListView Navigation'),
),
body: Center(
child: RaisedButton(
child: Text('Fetch Data'),
onPressed: () {
fetchData().then((data) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ScreenPage(jsonData: jsonEncode(data)),
),
);
}).catchError((error) {
Fluttertoast.showToast(
msg: 'Failed to fetch data',
toastLength: Toast.LENGTH_SHORT,
);
});
},
),
),
);
}
}
在上述示例代码中,我们使用http包发送HTTP请求获取数据,并使用ListView.builder构建一个可滚动的列表视图。当用户点击列表项时,会显示一个提示信息。在点击按钮时,会触发fetchData方法来获取数据,并通过Navigator.push方法导航到新屏幕,并将数据以json格式传递给新屏幕。
这个示例中使用了http和fluttertoast依赖,你可以在pubspec.yaml文件中添加如下依赖:
dependencies:
flutter:
sdk: flutter
http: ^0.13.3
fluttertoast: ^8.0.8
这是一个简单的示例,你可以根据自己的需求进行修改和扩展。希望对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云