9. Dialog 구성 요소

2907 단어
Flutter는 SimpleDialog와 AlertDialog 두 가지 유형의 대화 상자를 제공합니다.SimpleDialog는 추가 힌트나 조작을 표시할 수 있는 간단한 대화상자이고, AlertDialog는 사용자의 조작을 중단시킬 수 있는 대화상자로 사용자가 확인해야 하는 대화상자이며, 다음은 코드로 사용법을 설명한다.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Test',
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Test')
        ),
//        body: new MyAlertDialogView()
        body: new MySimpleDialogView(),
      ),
    );
  }
}

class MyAlertDialogView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new RaisedButton(
      child: new Text('  AlertDialog'),
      onPressed: () {
        showDialog(
          context: context,
          barrierDismissible: false, //              ,        
          builder: (BuildContext context) {
            return new AlertDialog(
              title: new Text('  '),
              content: new Text('    Windows 7  2020 1       ,                          Windows 10。'),
              actions: [
                new FlatButton(
                  child: new Text('   '),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      },
    );
  }
}

class MySimpleDialogView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new RaisedButton(
      child: new Text('  SimpleDialog'),
      onPressed: () {
        showDialog(
          context: context,
          builder: (BuildContext ctx) {
            return new SimpleDialog(
              title: new Text('  SimpleDialog'),
              children: [
                new SimpleDialogOption(
                  onPressed: () { Navigator.pop(context); },
                  child: const Text('  '),
                ),
                new SimpleDialogOption(
                  onPressed: () { Navigator.pop(context); },
                  child: const Text('  '),
                ),
              ],
            );
          }
        );
      },
    );
  }
}

위 코드는 각각 SimpleDialog와 AlertDialog의 기본 사용법을 보여 줍니다.주의해야 할 것은 여기에 버튼과 대화상자를 표시하는 논리를 MyApp류에 직접 쓰지 않고 두 개의 StatelessWidget로 나뉘어 썼다는 것이다. 만약에 버튼과 대화상자를 표시하는 논리를 MyApp의build 방법에 직접 쓰면 오류가 발생할 수 있다. 구체적인 오류 메시지는 다음과 같다.
Navigator operation requested with a context that does not include a Navigator.

네비게이션 조작에 Navigator가 포함되지 않은 상하문 대상이 필요하다는 뜻이다. 만약에 우리가 showDialog의 논리를 MyApp의build 방법에 썼을 때 MaterialApp의 상하문 대상을 사용했는데 이 상하문 대상은 Navigator를 포함하기 때문에 오류가 발생할 수 있다.위의 코드가 시뮬레이터에서 실행되는 효과는 아래 그림과 같습니다

좋은 웹페이지 즐겨찾기