Skip to content

ErolC/MRouter

Repository files navigation

MRouter

Maven Central License Latest build

MRouter是一个适用于compose-multiplatform的路由库

其实现了基础的路由,参数传递,动画,手势,生命周期,共享元素以及局部路由等一系列功能。

安装

在项目的build.gradle.kts中添加以下依赖,同步后即可开始使用

    commonMain.dependencies {
            implementation("cn.erolc.mrouter:core:<version>")
    }

简单使用

我们首先需要在common中创建Compose页面的根部,然后实现各个平台的入口即可。代码如下

准备两个页面

class HomeViewModel : ViewModel() {
    val result = mutableStateOf("")
}

@Composable
fun Home(){
    val pageScope = LocalPageScope.current
    
    val viewModel = viewModel(::HomeViewModel) //use viewModel
    
    var result by remember { viewModel.result }

    Button(onClick={
        pageScope.route("second") { // route to second page
            argBuild{ // build the args
                putString("key","value")
            }
            onResult{
                result = it.getString("result","") //get return data 
            }
        }
    }){
        Text(result) //data
    }
    
}

@Composable
fun Second(){
    val pageScope = LocalPageScope.current
    val args = rememberArgs()
    Button(onClick={
        pageScope.setResult(bundleOf("result" to "success")) // set return data
        pageScope.backPressed() // back to home page
    }){
        Text(args.getString("key")) //value
    }
}

common

common中使用RouteHost

@Composable
fun App() {
    MaterialTheme {
        RouteHost("home") {
            page("home") {
                Home()
            }
            page("second") {
                Second()
            }
        }
    }
}

RouteHost是路由的起点,通过page方法将composable注册成页面,以上示例在打开app时将首先展现Home()页面.

android

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            App() // 使用common的App()
        }
    }
}

desktop

fun main() = mRouterApplication {
    App()
}

ios

fun MainViewController() = ComposeUIViewController {
    App()
}

wasmJs

@OptIn(ExperimentalComposeUiApi::class)
fun main() {
    CanvasBasedWindow(canvasElementId = "ComposeTarget") {
        App()
    }
}