Flutter中的Provider(九)-基本Provider-Provider
阿新 • • 發佈:2020-12-24
技術標籤:flutter
Provider的原本作用是解耦,進行狀態管理,這裡使用最基礎的Provider進行這個作用的演示
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Material App', home: Scaffold( appBar: AppBar( title: Text('Material App Bar'), ), body: Home(), ), ); } } class Home extends StatelessWidget { @override Widget build(BuildContext context) { return Provider<String>( create: (_)=>'1', child: Center( child: ChildWidget(), ), ); } } class ChildWidget extends StatelessWidget {//在這裡不用明確的把數值傳遞過來 @override Widget build(BuildContext context) { var select = context.select<String,int>((value){//輸入,對應String,源自Provider提供的內容 return int.parse(value);//輸出,對應int,具體參考Selector }); return Text('獲取的內容:$select'); } }