화면 UI를 새로 그리는 역할을 함
StatelessWidget에서는 최초 1화만 실행됨.
StatefulWidget은 build()함수가 빈번하게 호출됨
initStat(): 위젯이 생성될 때 최초 1회 호출
build(): 위젝 상태가 변경될 때마다 호출
setState(): 프레임워크와 개발자로부터 호출
dispose(): 위젯 완전 종료
StatefulWidget은 변경된 사항이 있을 경우 setState()를 통해 상태를 갱신
Provider pattern
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();
}
}