[TIL]221005 - Flutter: Provider

Jimin·2022년 10월 5일
0
post-custom-banner

Statelsess와 Stateful의 동작 비교

build()

  • 화면 UI를 새로 그리는 역할을 함

  • StatelessWidget에서는 최초 1화만 실행됨.

  • StatefulWidget은 build()함수가 빈번하게 호출됨

    • lifecycle 메서드 활용

      initStat(): 위젯이 생성될 때 최초 1회 호출
      build(): 위젝 상태가 변경될 때마다 호출
      setState(): 프레임워크와 개발자로부터 호출
      dispose(): 위젯 완전 종료


    상태관리

  • StatefulWidget은 변경된 사항이 있을 경우 setState()를 통해 상태를 갱신

  • Provider pattern

    • 하위 위젯들은 value 공유 가능
    • 사용할 위젯은 Consumer를 통해 소비

Provider 패키지 설치

dependencies:
  flutter:
    sdk: flutter
  provider: ^6.0.3

//main.dart

import 'package:flutter/material.dart';
import 'package:opensource_6/second_page.dart';
import 'package:provider/provider.dart';
import 'first_page.dart';
import 'counter.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<Counter>(
        create: (BuildContext context) => Counter(),
        child: MaterialApp(
          title: 'Navigator Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          initialRoute: '/first',
          routes: {
            '/first': (context) => FirstPage(),
            '/second': (context) => SecondPage()
          },
        ));
  }
}
//first_page

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'counter.dart';
import 'Student.dart';

class FirstPage extends StatelessWidget {
  var cnt;

  @override
  Widget build(BuildContext context) {
    cnt = Provider.of<Counter>(context, listen: true);
    return Scaffold(
      appBar: AppBar(
        title: Text('First'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: ElevatedButton(
              child: Text('Next Page'),
              onPressed: (){
                Navigator.pushNamed(context, '/second',);
              },
            ),
          ),
          Text('${cnt.number}')
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          cnt.add();
        },
        child: Icon(Icons.add),
        backgroundColor: Colors.blue,
      ),
    );
  }
}
//second_page

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'counter.dart';
import 'Student.dart';

class SecondPage extends StatelessWidget {

  // final String data;
  var cnt;
  @override
  Widget build(BuildContext context) {
    cnt = Provider.of<Counter>(context, listen: false);
    return Scaffold(
        appBar: AppBar(
          title: Text('Second'),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Center(
              child: ElevatedButton(
                child: Text('Previous Page'),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
            ),
            Consumer<Counter>(
              builder: (context, counter, child) {
                return Text('${counter.number}');
              },
            ),
          ],
        ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          cnt.add();
        },
        child: Icon(Icons.add),
        backgroundColor: Colors.blue,
      ),
    );
    return Container();
  }
}
post-custom-banner

0개의 댓글