I'm newbie in Flutter.
I have very simple app
main.dart:
import 'package:dart_test/views/widgets/items/pack_items.dart';
import 'package:dart_test/views/widgets/items/pack_row.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("app build");
var pdata =
PackData(packId: 'npack1', name: 'Pack1', name_ru: 'пак 1', nImages: 5);
//print("~w:$contW");
return MaterialApp(
home: PackBody(data: pdata, offset: 0).build(context));
}
}
PackBody.dart:
class PackBody extends ListItem {
final PackData data;
final int offset;
PackBody({required this.data, required this.offset});
@override
Widget build(BuildContext context) {
var ar = 896.0 / 768;
//var contWidth=MediaQuery.of(context).size.width;
return Container(
width: MediaQuery.of(context).size.width,
height: 50,
child: Text('khkljgkjhgkjhg'),
);
}
}
And it throws an exception:
I tried to wrap PackBody
with MediaQuery
- no luck
Shouldn't MaterialApp
provide MediaQuery
down to the hierarchy?
CodePudding user response:
What you are doing is the same as writing:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("app build");
var pdata = PackData(packId: 'npack1', name: 'Pack1', name_ru: 'пак 1', nImages: 5);
//print("~w:$contW");
return MaterialApp(
home: Container(
width: MediaQuery.of(context).size.width,
height: 50,
child: Text('khkljgkjhgkjhg'),
),
);
}
}
The MediaQuery
widget establishes a subtree in which media queries resolve to the given data. MaterialApp
introduces a MediaQuery
and keeps it up to date with the current screen metrics as they change. In order for MediaQuery.of(context)
to work it needs to be in that subtree, and from the previous code sample I provided it clearly is not.