Skip to content

Instantly share code, notes, and snippets.

@hongsw
Created May 16, 2023 23:59
Show Gist options
  • Save hongsw/341ff6fea3edba273ecdaf43a7b93f8b to your computer and use it in GitHub Desktop.
Save hongsw/341ff6fea3edba273ecdaf43a7b93f8b to your computer and use it in GitHub Desktop.
StatefulWidget, Callback을 이용한 상태 관리

StatefulWidget, Callback을 이용한 상태 관리

Created with <3 with dartpad.dev.

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Form Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: FirstPage(),
);
}
}
class FirstPage extends StatefulWidget {
@override
_FirstPageState createState() => _FirstPageState();
}
class _FirstPageState extends State<FirstPage> {
String _myVariable = "Initial Value";
void _changeMyVariable(String newValue) {
setState(() {
_myVariable = newValue;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('My Variable: $_myVariable'),
ElevatedButton(
child: Text('Go to Second Page'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondPage(changeMyVariable: _changeMyVariable),
),
);
},
),
],
),
),
);
}
}
class SecondPage extends StatelessWidget {
final Function changeMyVariable;
SecondPage({required this.changeMyVariable}) : super();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Page'),
),
body: Center(
child: ElevatedButton(
child: Text('Change My Variable'),
onPressed: () {
changeMyVariable("New Value");
Navigator.pop(context);
},
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment