Hello Fluttermates,
我正在尝试使用mediaquery获取屏幕尺寸并将其存储在一个名为size的变量中。 我正在另一个屏幕上执行此操作 这给了我这个错误
无法在初始化程序中访问实例成员“上下文”。 (位于[appname] lib \ seriveSelection.dart:45处的implicit_this_reference_in_initializer)
import 'package:flutter/material.dart';
class home extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<home> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.white,
centerTitle: true,
automaticallyImplyLeading: false,
title: Text(
'Home',
style: TextStyle(
fontSize: 30,
color: Colors.black,
fontFamily: "Antipasto"
),
),
),
body: myapp(),
);
}
}
class myapp extends StatefulWidget {
@override
_myappState createState() => _myappState();
}
class _myappState extends State<myapp> {
var size = MediaQuery.of(context).size;
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Container(
child: Column(
children: [
Container(
width: 200,
child: Card(
child: Text(
'Welcome'
),
),
)
],
),
)
);
}
}
答案 0 :(得分:1)
mediaquery在实例化状态后立即执行,这对于访问上下文还为时过早,该上下文尚未准备好。
将其移至build()
方法内部。
class _myappState extends State<myapp> {
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return SingleChildScrollView(