the below code is one of my many pages for my app. I'm trying to set this page up with the LayoutBuilder so that it'll work like a quiz page with the bottom half/section would hold 3 to 4 TextButtons and the top half/section would hold the question and possibly display a picture. I did some research and I found that you're able to use the LayoutBuilder to set up containers to be half of the screen. However, when I tried doing that here with this code, I got A LOT of exceptions thrown. So I was wondering if there was a better way to divide the screen in half (or possibly 1/4, 1/4, & 1/2) for a quiz-like layout. Thank you for your help!
quiz.dart
class Quiz extends StatelessWidget {
const Quiz({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Quiz'),
),
body: Column(
children: [
Align(alignment: Alignment.topCenter,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return Container(
height: constraints.maxHeight / 2,
// widthdouble.infinity,
);
},
)),
Align(alignment: Alignment.topCenter,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return Container(
height: constraints.maxHeight / 2,
// widthdouble.infinity,
color: const Color.fromRGBO(155, 205, 255, 0.8),
child: Column(children: [
/* TextButton(onPressed: onPressed, child: child),
TextButton(onPressed: onPressed, child: child),
TextButton(onPressed: onPressed, child: child), */
Text('Option A'),
Text('Option B'),
Text('Option C'),
],),
);
},
)),
],
));
}
}
CodePudding user response:
You can try to move the LayoutBuilder
up, so that you can use the constraints for the children of your Column
:
class Quiz extends StatelessWidget {
const Quiz({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Quiz')),
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return Column(
children: [
Container(
height: constraints.maxHeight / 2,
color: Colors.green.shade300,
),
Container(
height: constraints.maxHeight / 2,
color: Colors.blue.shade300,
),
],
);
},
),
);
}
}
CodePudding user response:
It can be done in an easy way with the help of an expanded widget.Create 2 expanded widget with flex you need so that you can divide the screen as you wish.
enter code here
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
flex: 1,
child: Container(
color: Colors.amberAccent,
),
),
Expanded(
flex: 1,
child: Container(
color: Colors.lightBlue,
),
),
],
);
}
}