Skip to content

Instantly share code, notes, and snippets.

@mnazim
Last active July 4, 2022 13:30
Show Gist options
  • Save mnazim/7ac94f3615b4c30b60ee47fca09b64d1 to your computer and use it in GitHub Desktop.
Save mnazim/7ac94f3615b4c30b60ee47fca09b64d1 to your computer and use it in GitHub Desktop.
import 'dart:convert';
void main() {
String someJson = """{
"iceCreams": [
{
"flavor": "raspberry",
"color": "red"
},
{
"flavor": "banana",
"color": "yellow"
}
]
}""";
var json = jsonDecode(someJson);
// (Part 2) should print raspberry
// print(json[[0]["flavor"]);
// mnazim:
// json is a map, not an array.
// It cannot be accessed with an index.
print(json['iceCreams'][0]['flavor']);
// (Part 3) how is this even possible?
// print(json["iceCreams"][0].toUpperCase());
// mnazim:
// json['iceCreams'][0] is a map.
// it must be cast to string before trying to uppercase it, like so,
print(json['iceCreams'][0].toString().toUpperCase());
// or like so,
print('${json['iceCreams'][0]}'.toUpperCase());
}
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
// mnazim: made key nullable
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: Column(
children: [
for (int i = 0; i < 3; i++)
Column(
children: [
Text(
"Set $i",
style: Theme.of(context).textTheme.headline6,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: MyListView(i: i),
),
],
),
],
),
),
);
}
}
class MyListView extends StatelessWidget {
const MyListView({
Key? key,
required this.i,
}) : super(key: key);
final int i;
@override
Widget build(BuildContext context) {
// mnazim: ListView does not have an intrinsic height,
// since it was nested in a column and column takes the height of it's children,
// this constraint was not solvable by flutter automatically.
// solution:
// extract to a separate widget, so MediaQuery can be accessed.
// provide a fixed height (based on available height) for the ListView
return SizedBox(
height: MediaQuery.of(context).size.height / 4,
child: ListView(
children: [
for (int j = 0; j < 100; j++)
Center(
child: Text("{$i, $j}"),
),
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment