Skip to content

Instantly share code, notes, and snippets.

@hongsw
Last active November 13, 2025 07:59
Show Gist options
  • Select an option

  • Save hongsw/7970b0ec60d2074ac715c7360ff85884 to your computer and use it in GitHub Desktop.

Select an option

Save hongsw/7970b0ec60d2074ac715c7360ff85884 to your computer and use it in GitHub Desktop.
setState로 배경색도 변경됨(비효율적)
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(const SetStateApp());// ChangeNotifierProvider
}
// class ColorProvider ... ChangeNotifier
class SetStateApp extends StatelessWidget {
const SetStateApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: SetStateHomePage(),
);
}
}
class SetStateHomePage extends StatefulWidget {
const SetStateHomePage({super.key});
@override
State<SetStateHomePage> createState() => _SetStateHomePageState();
}
class _SetStateHomePageState extends State<SetStateHomePage> {
int _count = 0;
Color _bgColor = Colors.white;
final _rnd = Random();
void _changeWithSetState() { /// -->? ColorProvider 의 함수로 이동되어야함
setState(() {
_count++; // 의도된 UI업데이트
});
// 변경되지 않아도될 UI 업데이트
_bgColor = Colors.primaries[_rnd.nextInt(Colors.primaries.length)];
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: _bgColor, // ← setState 호출될 때마다 같이 변경
appBar: AppBar(title: const Text('setState 예제')),
body: Center(
child: Text(
'$_count', // context.watch<CounterProvider>().count
style: const TextStyle(fontSize: 60, fontWeight: FontWeight.bold),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _changeWithSetState,
child: const Icon(Icons.color_lens),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment