flutter

Provider 예제

paulaner80 2021. 4. 8. 09:43
반응형
import 'package:flutter/material.dart';
import 'package:flutter_test_widget/counter.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        brightness: Brightness.dark,
        primaryColor: Colors.amber,
        textTheme: TextTheme(
          headline1: TextStyle(color: Colors.teal)
        ),
        buttonTheme: ButtonThemeData(
          buttonColor: Colors.amber,
          textTheme: ButtonTextTheme.primary
        )
      ),
      home: MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (_)=>Counter(0))
        ],
        child: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title:Text("Example")),
      body: Center(
        child: Column(
          children: [
            CountWidget(),
            CountConsumer(),
            CountSelector()
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        key:const Key('increase_action-button'),
        onPressed: ()=>context.read<Counter>().inCreaseCounter(),
        tooltip: "Increase",
        child: const Icon(Icons.add),
      ),
    );
  }
}



class CountWidget extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Text(
      '${context.watch<Counter>().count}',
      key : const Key('counterState'),
      style: Theme.of(context).textTheme.headline4,
    );
  }
}


//리빌드 최적화 시킬 수 있음. 방법은 이해 못함.
//It helps with performance optimisation
// by providing more granular rebuilds.
class CountConsumer extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Consumer<Counter>(
      builder: (context, counter, child){
        return Text('${counter.count}',
            style: Theme.of(context).textTheme.headline2);
      },
    );
  }
}

class CountSelector extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Selector<Counter, int>(builder: (context, data, child){
      return Text('$data',
          style: Theme.of(context).textTheme.headline3);
    }, selector: (buildContext, counter){
      return counter.count;
    });
  }
}

'flutter' 카테고리의 다른 글

dart generator  (0) 2021.09.09
dart future then  (0) 2021.04.09
dart functor  (0) 2020.12.28
flutter - firebase 로그인, 로그아웃  (0) 2020.12.21
isolate를 이용하여 데이터 처리하기  (0) 2020.12.18