3

I am working on a project for using Flutter web and js size is getting increasing as I add features which is normal. I was looking at deferred import for Flutter and tried I out where I am getting split files as

List of files on build with size

I ran flutter run -d chrome which was working fine as I came to know deferred is ignored in debug build and when I ran with http-server npm package nothing is coming even looking at network request it was requesting part files but nothing is being displayed on screen and even no errors in console. I know Flutter Web recently move to beta so there might be optimisations like specially reducing size of main.dart.js but this should work according to doc.

Network request

Code

main.dart.js

import 'package:flutter/material.dart';
import 'package:split_test/page1.dart' deferred as page1;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          child: page1.Page1(),
        ),
      ),
    );
  }
}

page1.dart

import 'package:flutter/material.dart';
import 'package:split_test/page2.dart' deferred as pag2;

class Page1 extends StatelessWidget {
  const Page1({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Column(
          children: <Widget>[
            Text('Page1'),
            GestureDetector(
              onTap: () => Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => pag2.Page2(),
                ),
              ),
              child: Text('Go to page 2'),
            )
          ],
        ),
      ),
    );
  }
}

page2.dart.js

import 'package:flutter/material.dart';

class Page2 extends StatelessWidget {
  const Page2({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: Column(
            children: <Widget>[
              Text('Page2'),
              GestureDetector(
                onTap: () => Navigator.pop(context),
                child: Text('<- Back'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

Thank you for your help. I was looking at this issue.

1 Answer 1

3

You can use Dart's deferred imports for doing something like that.

See this for more details : https://dart.dev/guides/language/language-tour#lazily-loading-a-library

Also for flutter there is an important discussion going on about this in this issue here regarding giving proper support for code splitting for flutter web : https://github.com/flutter/flutter/issues/50196

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.