1. HTTP 请求:
使用 http 包来执行网络请求:
dependencies:
http: ^0.14.0
import 'dart:convert';
import 'package:http/http.dart' as http;
void fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
print('Title: ${data['title']}');
} else {
print('Failed to load data');
}
}
2. 路由导航:
使用 fluro 包来实现更灵活的路由导航:
dependencies:
fluro: ^2.0.3
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final FluroRouter router = FluroRouter();
MyApp() {
// 定义路由
router.define('/page/:id', handler: Handler(handlerFunc: (_, params) {
return MyPage(params['id'][0]);
}));
}
@override
Widget build(BuildContext context) {
return MaterialApp(
onGenerateRoute: router.generator,
home: HomeScreen(router: router),
);
}
}
class HomeScreen extends StatelessWidget {
final FluroRouter router;
const HomeScreen({Key? key, required this.router}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Fluro Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
router.navigateTo(context, '/page/123');
},
child: Text('Navigate to Page'),
),
),
);
}
}
class MyPage extends StatelessWidget {
final String id;
const MyPage(this.id);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Page $id'),
),
body: Center(
child: Text('Page $id Content'),
),
);
}
}
3. 状态管理:
使用 provider 包来进行简单的状态管理:
dependencies:
provider: ^6.2.2
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class Counter with ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => Counter(),
child: MaterialApp(
home: HomeScreen(),
),
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final counter = Provider.of<Counter>(context);
return Scaffold(
appBar: AppBar(
title: Text('Provider Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Count: ${counter.count}'),
SizedBox(height: 16),
ElevatedButton(
onPressed: () {
counter.increment();
},
child: Text('Increment'),
),
],
),
),
);
}
}
这些是一些Flutter中常用的包及其基本用法的示例。根据你的应用需求,你可以使用不同的包来提供各种功能和服务。要了解更多Flutter包,请查看[Dart包的官方网站](https://pub.dev/)。
转载请注明出处:http://www.zyzy.cn/article/detail/9604/Flutter