- Native Splash Screen in Flutter Using Lottie
- AbedElaziz Shehadeh
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: Hoarfroster
- Proofreader: Zenblo, KeepmovingLjzy
We could of course add animation startup effects to the Flutter application directly using the Dart code, however, The Flutter application is launched as a FlutterActivity or FlutterViewController on Android and iOS, which causes the Flutter application to spend some time before the first frame is actually drawn. Therefore, setting up the splash screen at app launch will lead to a better user experience.
It is worth noting that the official documentation of Flutter can easily add a still image to the launch page, and this page has sufficient documentation information for us to use. We actually just need to add images to the Android Drawable folder and iOS Resources folder, and then use them in Android styles.xml and iOS launchscreen.storyboard. However, I couldn’t find references to how to use Lottie and other libraries to animate an application’s launch page, and that’s what I’ll cover in this article.
Why do we use Lottie?
Lottie is a multi-platform (Android and iOS) library for parsing jSON-formatted animations exported by Adobe After Effects through Bodymovin and rendering them locally. This means that animations are designed by professional designers and exported using JSON files, making it easy for us developers to render animations with no extra effort. In this tutorial, we will use a free sample file created by LottieFiles, the original file can be found here. Let’s start our journey of Flutter + Lottie.
First let’s create a new Flutter project and then perform the following steps:
Android
- Add Lottie dependencies to your project first
app/build.gradle
File (as opposed to the Flutter applicationandroid/app/build.gradle
File) (I also added Constraint Layout here)
dependencies {
...
implementation "Com. Reality. The android: Lottie: 3.5.0." "# Current version3.6. 0
implementation "Androidx. Constraintlayout: constraintlayout: 2.0.4."# implementation"Com. Android. Support. The constraint, the constraint - layout: 2.0.4"But Lottie2.8+ only supports AndroidX projects... }Copy the code
- in
AndroidManifest.xml
In the deletename
For the IO. Flutter. Embedding. Android. SplashScreenDrawable<meta-data>
Mark and replaceactivity
Under the labelLaunchTheme
为NormalTheme
Your file now looks like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.abedelazizshe.flutter_lottie_splash_app">
<! -- io.flutter.app.FlutterApplication is an android.app.Application that calls FlutterMain.startInitialization(this); in its onCreate method. In most cases you can leave this as-is, but you if you want to provide additional functionality it is fine to subclass or reimplement FlutterApplication and put your custom class here. -->
<application
android:name="io.flutter.app.FlutterApplication"
android:label="flutter_lottie_splash_app"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/NormalTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density |uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<! -- Specifies an Android theme to apply to this Activity as soon as the Android process has started. This theme is visible to the user while the Flutter UI initializes. After that, this theme continues to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<! -- Don't delete the meta-data below. This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
Copy the code
You can be in/android/app/res/values/styles. The definition of XML delete folder LaunchTheme, because you will no longer need it.
-
Create a raw directory in the /android/app/res/values folder and copy the generated.json file (whether you created your own file or downloaded the free sample from the link above). In this case, the JSON folder name should be splash_screen.json.
-
To use the.json file and display the animated view, we need to create a launch view class with its layout. Under /android/app/res, create a new directory called Layout (if it doesn’t already exist), then create a new layout resource file called splash_view.xml. Open the XML file and change the code to:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.airbnb.lottie.LottieAnimationView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:lottie_autoPlay="true"
app:lottie_rawRes="@raw/splash_screen"
app:lottie_loop="false"
app:lottie_speed="1.00" />
</androidx.constraintlayout.widget.ConstraintLayout>
Copy the code
In this example, I set the animation to autoplay, set the playback speed to 1.0, and disable looping. You can use different values as needed. The most important part is the app:lottie_rawRes property, which defines the JSON file we will use to add to the RAW directory. Now we need to create the class that launches the view. Let us in/android/app/SRC/main/kotlin/YOUR PACKAGE – to create a new kotlin class NAME. Name this class SplashView and change its contents to:
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import io.flutter.embedding.android.SplashScreen
class SplashView : SplashScreen {
override fun createSplashView(context: Context, savedInstanceState: Bundle?).: View? =
LayoutInflater.from(context).inflate(R.layout.splash_view, null.false)
override fun transitionToFlutter(onTransitionComplete: Runnable) {
onTransitionComplete.run()
}
}
Copy the code
As you can see, this view Inflate the splash_view layout file. The last step is to tell MainActivity about our custom launch view.
5. Go to the android/app/SRC/main/kotlin/YOUR PACKAGE – NAME folder, and then click MainActivity. Kt. FlutterActivity provides a method called provideSplashScreen, modified to:
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.SplashScreen
class MainActivity: FlutterActivity() {
override fun provideSplashScreen(a): SplashScreen? = SplashView()
}
Copy the code
The project directory should now look like this:
This is how Lottie builds Splash’s startup page on Android. Just run the app and you can see the animation when the app launches.
iOS
Let’s add a launch page in iOS:
- Open the project directory, click the ios folder, and then double-click
Runner.xcworkspace
Open your project.
2. Click main.storyboard and you will see a layout editor with a screen. We need to add a new ViewController, which will be our startup page (you can do this by clicking the + sign in the upper right corner). Click and a window will pop up. Enter View Controller search in the input box and drag the control to the editor, as shown in the screenshot below:
- After completing step 2, you will see two screens. Select the new View Controller and click
attributes inspector
And then click againis initial view controller
.
- We need to start
ios/Podfile
Add Lottie dependencies to the file;
pod 'lottie-ios'
Copy the code
The file should now look like this: (Editor’s note: you may have changed some of the Settings, this is just an example)
#platform :ios, '9.0'
target 'Runner' do
use_frameworks!
pod 'lottie-ios'
end
Copy the code
Then run the application (make sure the command line is currently in the ios directory. If not, use the CD command to move your directory to the ios directory.
pod install
Copy the code
- Use Xcode to put your generated
.json
Drag the file to the root directory inCopy items if needed
Option), this file may be your own creation, or you may have downloaded a free sample from the link above. In this case it’s calledsplash_screen.json
.
6. With the dependencies and splash_screen.json file added, we can create our initial view controller that will handle the animation displayed. Open your ios project and create a new Swift file called SplashViewController in the project root (relative to the Flutter root: /ios/Runner). Before we write anything in the class, let’s modify Appdelegate. swift to create the FlutterEngine. If you skip this step, you cannot jump to the FlutterViewController after the animation splash screen finishes playing.
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
lazy var flutterEngine = FlutterEngine(name: "MyApp")
override func application(
_ application: UIApplication.didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// Runs the default Dart entrypoint with a default Flutter route.
flutterEngine.run()
// Used to connect plugins (only if you have plugins with iOS platform code).
GeneratedPluginRegistrant.register(with: self.flutterEngine)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Copy the code
Here we create a called MyApp FlutterEngine (you can decide its name), and then run the engine in application of didFinishLaunchingWithOptions and registered the plugin in the engine. It’s important to note that the default code is GeneratePluginRegistrant register (with: self), please make sure that it is to the self. FlutterEngine registration.
- Having done that, now we can prepare
SplashViewController
To display the animation. Navigate to theFlutter
View Controller, modify the code as:
import UIKit
import Lottie
public class SplashViewController: UIViewController {
private var animationView: AnimationView?
public override func viewDidAppear(_ animated: Bool) {
animationView = .init(name: "splash_screen")
animationView!.frame = view.bounds
animationView!.contentMode = .scaleAspectFit
animationView!.loopMode = .playOnce
animationView!.animationSpeed = 1.00
view.addSubview(animationView!)
animationView!.play{ (finished) in
self.startFlutterApp()
}
}
func startFlutterApp(a) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let flutterEngine = appDelegate.flutterEngine
let flutterViewController =
FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
flutterViewController.modalPresentationStyle = .custom
flutterViewController.modalTransitionStyle = .crossDissolve
present(flutterViewController, animated: true, completion: nil)}}Copy the code
In viewDidAppear, we initialize the animated view with the added splash_screen.json file. You can modify playback Settings such as loopMode, animationSpeed, etc. After the animation ends, we will launch our Flutter application.
To get the FlutterViewController, we must get an instance of the FlutterEngine we created and run in Appdelegate.swift.
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let flutterEngine = appDelegate.flutterEngine
let flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
Copy the code
Then launch the view controller using present(completion :).
- Now it’s time to create step 2
ViewController
与SplashViewController
Classes are linked. Click on theMain.storyboard
And choose a new oneViewController
And then fromidentity inspector
Select theSplashViewController
, as shown in the screenshot:
- The last step is setup
Main.storyboard
The home screen, replacedLauncherScreen.storyboard
. Click Runner and selectGeneral
TAB, indeployment info
Down, from the dropdown menuMain interface
Set toMain, as shown in the screenshot:
Generate and run the application and you should be able to see the animation’s launch page:
That’s it, you’ve now generated animated launch pages for Android and iOS applications. The full source code and demo application are available here:
AbedElazizShe/flutter_lottie_splash_app
If you have any questions, or have a better way to solve this problem, please feel free to leave a comment.
- This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.