본문 바로가기

Flutter-플러터/플러터 공부

23.6.26 수업 정리 -Provider

반응형

 상태관리는 == data 관리 체계


 

 

동기 /비동기 == 프로세스 

비동기 = 선호출 후에 값 받기 (예약) 
동기 = 순차적인 흐름 (요리, 서버 데이터 받기)

 

클래스의 "필드"

widget이 stateful 클래스에서 변수 접근 방법 

context == 앱에 대한 내부적인 정보 : 메타데이터 

 


 

상태관리 

아파트 분리수거 변경일자를 
101호에서 전파하느냐 
사무실에서 "동시" 전파하느냐 

 

- counter 모델에서 chagneNotifier 클래스 사용 

import 'package:flutter/material.dart';

// 방송하는 코드
class Countermodel extends ChangeNotifier {
  int counter = 0;

  void increase() {
    counter++;
    notifyListeners(); // 방송 실행 코드
  }

  void minus() {
    counter--;
    notifyListeners();
  }
}

 

minusscreen 에 컨슈머를 사용해서 어플 제작 

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

import '../model/counter_model.dart';

class MinusScreen extends StatefulWidget {
  const MinusScreen({super.key});

  @override
  State<MinusScreen> createState() => _MinusScreenState();
}

class _MinusScreenState extends State<MinusScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.red,
        title: Text('minus screen'),
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Consumer<Countermodel>(
                builder: (context, Countermodel countermodel, child) {
              return Text(
                countermodel.counter.toString(),
                style: TextStyle(fontSize: 30),
              );
            }),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Provider.of<Countermodel>(context, listen: false).minus();
        },
        child: Icon(Icons.remove),
        backgroundColor: Colors.red,
      ),
    );
  }
}

 Addscreen에  provider 적용 

import 'package:flutter/material.dart';
import 'package:jhc_provider/model/counter_model.dart';
import 'package:jhc_provider/screen/minus_screen.dart';
import 'package:provider/provider.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => Countermodel()),
      ],
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: const MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Consumer<Countermodel>(
                builder: (context, Countermodel countermodel, child) {
              return Text(
                countermodel.counter.toString(),
                style: TextStyle(fontSize: 30),
              );
            }),
            OutlinedButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => MinusScreen()),
                  );
                },
                child: Text('Go minus'))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Provider.of<Countermodel>(context, listen: false).increase();
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
반응형