FLUTTER/Common

2. Stateless Stateful

atawlee 2022. 9. 3. 23:07
import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text(
      'Hello, World!',
      style: Theme.of(context).textTheme.headline4,
    );
  }
}

dartpad.dev 사이트에서 new pad 하면 나오는 코드입니다.
Stateless 는 상태변화가 없는 위젯이라고 이해하면 간단한 내용 입니다.
화면상에 변화가 없기 때문에 동적으로 변화되는 화면을 만들기에는 부적합합니다.

// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

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

class _MyHomePageState extends State {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}


위 코드는 카운터 코드로 우측하단 버튼을 클릭하면 중앙의 카운터수가 올라갑니다.
Stateless Widget을 사용한 첫번째 코드와 다르게 Stateful widget을 사용하였고
하단 floatingActionButton에서 onPressed 이벤트에서 _incrementCounter 이벤트가 발생되도록 되어 있습니다. 상태변화가 있을시에는 setState() 함수를 사용하고 내부나 바깥에 상태변화에 사용되는 변수를 변경합니다. 

setState() 메서드가 발생되면 _MyHomePageSate의 build가 다시한번 호출되어 Text에 변경된$_counter 값이 보여지게 됩니다.