Flutter报错:No Material widget found Switch widgets require a Material widget ancestor

在Flutter开发中,如果出现如下报错信息
No Material widget found Switch widgets require a Material widget ancestor
Flutter报错:No Material widget found Switch widgets require a Material widget ancestor_第1张图片

一.问题原因分析:
1.首先你应该使用了material风格的控件,如Textfield,Switch等;
2.使用这些控件的时候在build方法中根Widget没有使用Scaffold作为根控件

二 解决方法: 知道了原因,在build方法中添加Scaffold作为根控件即可
eg:

import 'package:flutter/material.dart';

class SwitchAndCheckBoxPage extends StatefulWidget {
  @override
  _SwitchAndCheckBoxPageState createState() =>
      new _SwitchAndCheckBoxPageState();
}

class _SwitchAndCheckBoxPageState extends State {
  bool _switchSelected = false;
  bool _checkboxSelected = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: new Text('Switch And CheckBox'),
        ),
        body: Column(
          children: [
            Switch(
              value: _switchSelected,
              onChanged: (value) {
                setState(() {
                  _switchSelected = value;
                });
              },
            ),
            Checkbox(
              value: _checkboxSelected,
              activeColor: Colors.red,
              onChanged: (value) {
                setState(() {
                  _checkboxSelected = value;
                });
              },
            ),
          ],
        ));
  }
}

你可能感兴趣的:(Flutter)